package com.qf.login;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 记住我
 *
 * @USER: Administrator
 * @DATE: 2025/8/31 下午2:15
 * @VERSION: 1.0.0
 */
public class MyRememberMeService extends TokenBasedRememberMeServices {
    public MyRememberMeService(String key, UserDetailsService userDetailsService) {
        super(key, userDetailsService);
        // 设置令牌有效期（例如：7天，单位：秒）
        setTokenValiditySeconds(60 * 60 * 24 * 7);
        // 设置前端"记住我"复选框的参数名（需与表单一致）
        setParameter("rememberMe");
    }


    @Override
    public void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
        Cookie username = new Cookie("username", successfulAuthentication.getName());
        username.setMaxAge(60 * 60 * 24 * 7); // 设置有效期为7天
        username.setPath("/"); // 设置Cookie的路径
        response.addCookie(username); // 将Cookie添加到响应中

        super.onLoginSuccess(request, response, successfulAuthentication);
    }
}
